<template>
  <el-card>
    <template #header>
      <h3 class="user-add-title">添加用户</h3>
    </template>
    <!-- 
      表单校验：
        el-form
          1. rules 表单校验的规则
          2. model 表单数据
        el-form-item
          1. prop 
            指定表单校验具体规则
            指定数据（model）中校验的字段
     -->
    <el-form
      label-width="80px"
      class="user-add-form"
      :rules="rules"
      :model="user"
    >
      <el-form-item label="用户名称" prop="username">
        <el-input placeholder="请输入用户名称" v-model="user.username" />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input placeholder="请输入用户昵称" v-model="user.nickname" />
      </el-form-item>
      <el-form-item label="用户密码">
        <el-input
          type="password"
          placeholder="请输入用户密码"
          v-model="user.password"
        />
      </el-form-item>
      <el-form-item label="确认密码">
        <el-input
          type="password"
          placeholder="请输入确认密码"
          v-model="user.rePassword"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary">添加</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: "UserAdd",
  data() {
    return {
      user: {
        // 数据名称
        username: "",
        nickname: "",
        password: "",
        rePassword: "",
      },
      // 表单校验规则
      rules: {
        // 表单校验规则名称和数据名称必须一致
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 5, max: 20, message: "长度为5-20位", trigger: "blur" },
          {
            pattern: /^[0-9A-Za-z]$/,
            message: "只能是英文和数字",
            trigger: "blur",
          },
        ],
        nickname: [
          // 自定义校验规则
          {
            required: true,
            validator: this.nicknameValidator,
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    nicknameValidator(rule, value, callback) {
      /*
        rule 规则(表单项名称)
        value 表单项的值
        callback 必须要调用
          callback(xxx) 传入参数，说明表单校验失败
          callback()    不传入参数，说明表单校验成功
      */
      if (!/^[0-9A-Za-z]{5,20}$/.test(value)) {
        callback("只能包含英文和数字，长度为5-20位");
        return;
      }

      callback();
    },
  },
};
</script>

<style>
.user-add-title {
  margin: 0;
}
.user-add-form {
  width: 400px;
}
</style>